let W = null

class Watcher{
    constructor(obj,key){
        this.obj=obj
        this.key=key
        W=this
        this.get()
        W=null
    }
    get(){
        return this.obj[this.key]
    }
    update() {
        console.log('通知我更新了,去拿值');
        get()
    }
}


class Dep{
    constructor(){
        this.subs=[]
    }
    collect(watcher){
        this.subs.push(watcher)
    }
    notify(){
        console.log('通知更新');
        this.subs.forEach(item=>{
            item.update()
        })
    }
}


class Obsreve{
    constructor(obj){
        this.obj=obj
        if(Array.isArray(obj)){
            return this.arrayGo()
        }else{
            this.walk(obj)
        }
    }
    arrayGo(){
        this.obj.forEach(item => {
            observe(item)
        });
    }
    walk(obj){
        for (const key of Object.keys(obj)) {
            defineActive(obj,key,obj[key])
        }
    }

}

//定义一个defineActive,对每个数据进行数响应式处理
function defineActive(obj,key,value){

    observe(value)
   const dep= new Dep()
    Object.defineProperty(obj,key,{
        get(){

            if(W){
                dep.collect(W)
            }

            return value
        },
        set(newVal){
            value=newVal

            dep.notify()
        }
    })
}



function observe(obj){

    if(typeof obj!=='object'||obj===null)return

    new Obsreve(obj)
}




function Vue(options){
    this._data = options.data

    for (const key of Object.keys(this._data)) {
        Object.defineProperty(this,key,{
            get(){
                return this._data[key]
            },
            set(newVal){
                this._data[key]=newVal
            }
        })
    }
    observe(this._data)
}




const vm=new Vue({
    data:{
        name:'wang',
        age:19,
        hobby:[
            {id:'001',type:'工作'},
            {id:'002',type:'玩耍'},
            {id:'003',type:'旅游'}
        ]
    }
})


function get(){
    // console.log(new Watcher(vm,'name'));
    console.log(new Watcher(vm.hobby[0],'type'));
}

function set(){
    // vm.name='zhang'
    vm.hobby[0].type='学习'
}

get()
set()